<?php


class UsersVideo extends AppModel{
    
    public $belongsTo = array(
        'User' => array(
            'foreignKey' => 'users_id'
        )
    );
    
    
    public $hasOne = array(
        'VideosAdvice' => array(
            'foreignKey' => 'users_videos_id',
            'type' => 'LEFT'
        ),
    );
    
    public $hasMany = array(
        'UsersVideosComment' => array(
            'foreignKey' => 'users_videos_id'
        )
    );
    
    public function bindModelType($type){
        $this->bindModel(array(
            'hasOne' => array(
                $type => array(
                    'foreignKey' => 'users_videos_id'
                )
            )
        ));
    }
    
    
    public function getVideos($type, $options = array()){
        
        $videos = $this->find($type, 
                $options
        );
        
        $max = count($videos);
        $max = sizeof($videos);
        $i = 0;
        
        if ($max > 0 && !empty($videos)){
            do {
                if ($type == 'all' ){
                    $video = $videos[$i];
                }
                else{
                    $video = $videos;
                }
                $videoType = $video['UsersVideo']['type'];
                if ($videoType != 'null'){
                    $this->bindModelType($videoType);
                    $videoId = $video['UsersVideo']['id'];
                    $data = $this->$videoType->find('first', array(
                        'conditions' => array(
                            'users_videos_id' => $videoId
                        ),
                        'recursive' => false,
                        'fields' => array(

                        )
                    ));
                }
                if ($videoType != 'null')
                    $video[$videoType] = $data;

                if ($type == 'all'){
                    $videos[$i] = $video;
                }
                else{
                    $videos = $video;
                }
                $i++;
            } while($type == 'all' && $i < $max);
        
            $video['UsersVideo']['type'] = $video['UsersVideo']['type'] == 'null' ? false : $video['UsersVideo']['type'];

            return $videos;
        }
        else{
            return array();
        }
    }
    
    
    
    public function changeUsersVideoType($type, $videoId){
        $data = array(
            'UsersVideo' => array(
                'type' => $type,
                'id' => $videoId                
            )
        );
        $result = $this->save($data);
        return $result;
    }
    
}
?>
